import { FormEvent, SyntheticEvent, useEffect, useRef, useState } from 'react';
import { SearchContext } from '@indexea/sdk/context';
import { useIndexeaSearch } from '../hooks';

export type InputProps = {
  showLogo: boolean
}

/**
 * 搜索输入框组件，实现输入框自动完成的功能
 * @param context
 * @param attrs
 * @param showLogo
 * @param search
 * @returns
 */
export default function ({ showLogo }: InputProps) {
  const { selectLogo, context, layout: { input: attrs }, search, loading } = useIndexeaSearch();

  // Logo 的显示由多个因素决定，优先级最高的是 showLogo 参数，其次是 widget 中的设置
  const logo = selectLogo(showLogo);

  const queryRef = useRef<string>('');
  const [value, setValue] = useState<string>('');

  useEffect(() => {
    const q = context.q || '';
    if (queryRef.current !== q) {
      queryRef.current = q;
      setValue(q);
    }
  }, [context.q]);

  return (
    <form className="d-flex align-items-center mb-3" onSubmit={doSearch}>
      {logo && (
        <div className="logo">
          <a href="/" onClick={doHome}>
            <img src={logo} className="me-4" alt="logo" height="28"/>
          </a>
        </div>
      )}
      <div className="flex-grow-1">
        <input
          className="form-control"
          value={value}
          autoFocus={true}
          onChange={e => setValue(e.target.value)}
          disabled={loading}
        />
      </div>
      {attrs?.button && (
        <button type="submit" className="btn btn-primary ms-2" disabled={loading}>
          Search
        </button>
      )}
    </form>
  );

  function doSearch(e: FormEvent) {
    e.preventDefault();
    search(value);
  }

  function doHome(e: SyntheticEvent) {
    e.preventDefault();
    search('', 0);
  }
}
